package com.djl.sqtg.controller;
import com.aliyuncs.exceptions.ClientException;
import com.djl.sqtg.entity.Orders;
import com.djl.sqtg.entity.TzMonthData;
import com.djl.sqtg.service.IColonelService;
import com.djl.sqtg.service.IOrderService;
import com.djl.sqtg.util.SendMsgUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.Calendar;
import java.util.List;

@RestController
@Component //定时任务
public class ScheduleTaskController {
    public static final Integer CANCEL_ORDER_DAY = 1; //1天不付款自动取消
    public static final Integer AUTO_RECEIPT_DAY = 7; //7天自动收货
    public static final Integer AUTO_REVIEW_DAY = 7;  //7天自动评价

    @Autowired
    private IColonelService colonelService;
    @Autowired
    private IOrderService orderService;

//    @Scheduled(fixedRate = 2000)//每2秒执行一次
//    public void Test(){
//        System.out.println(LocalDateTime.now()+",获取的实时数据："+Math.random());
//    }

    @Scheduled(cron = "0 0 23 L * ?")//每月最后一天23点执行一次，把每个团长的每月营业额计算好，同时根据该月提成率计算出该团长该月的佣金，保存到数据库表中。
    public void MonthTurnoverTask(){
//        1、先获取所有团长的id，和本月该团长的提成
        List<TzMonthData> data = colonelService.getColonelIdRoyalty();
        System.out.println(data);
//        2、循环团长id，获取该团长该月的所有营业额
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        String monthstr=year+"-0"+month;
        System.out.println("今月：" + monthstr);
        for (int i=0;i<data.size();i++){
            data.get(i).setYearmonth(monthstr);
            float turnover =  colonelService.getMonthTurnover(monthstr, data.get(i).getCid());
            data.get(i).setTurnover(turnover);
            Integer royalty = data.get(i).getRoyalty();
            float money = turnover * royalty/100;
            data.get(i).setMoney(money);
            //  3、保存到数据库tzmonthdata表中
            Integer count = colonelService.getTzMonthDataByTzidMonth(data.get(i).getCid(),data.get(i).getYearmonth());
            System.out.println(count);
            if (count==null){
                System.out.println("数据库中无此团长本月的数据，故需添加");
                colonelService.addTzMonthData(data.get(i));
            }else {
                System.out.println("数据库中已经保存了该团长本月的数据");
            }
        }
    }

/*    @Scheduled(cron = "0 0 17 * * *")
    public void orderTask() throws ClientException {
        List<Orders> data=orderService.getOrdersByState(1);
        for (int i=0;i<data.size();i++){
            SendMsgUtil.sendSms(data.get(i).getUsername(),data.get(i).getTelep());
        }
    }*/

}
